package com.hzhr.iot.web.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.hzhr.iot.collect.sdk.model.command.allowOpenValve.AllowOpenValveModel;
import com.hzhr.iot.collect.sdk.model.command.clearFault.ClearFaultModel;
import com.hzhr.iot.collect.sdk.model.command.closeValve.CloseValveModel;
import com.hzhr.iot.collect.sdk.model.command.closeValve1.CloseValve1Model;
import com.hzhr.iot.collect.sdk.model.command.openValve.OpenValveModel;
import com.hzhr.iot.collect.sdk.model.command.openValve1.OpenValve1Model;
import com.hzhr.iot.collect.sdk.model.command.searchAlarm.SearchAlarmModel;
import com.hzhr.iot.collect.sdk.model.command.searchDayHis.SearchDayHisModel;
import com.hzhr.iot.collect.sdk.model.command.searchFreezingDay.SearchFreezingDayModel;
import com.hzhr.iot.collect.sdk.model.command.searchIp.SearchIpModel;
import com.hzhr.iot.collect.sdk.model.command.searchMonthHis.SearchMonthHisModel;
import com.hzhr.iot.collect.sdk.model.command.searchReportPeriod.SearchReportPeriodModel;
import com.hzhr.iot.collect.sdk.model.command.searchReportTime.SearchReportTimeModel;
import com.hzhr.iot.collect.sdk.model.command.setFreezingDay.SetFreezingDayModel;
import com.hzhr.iot.collect.sdk.model.command.setIp.SetIpModel;
import com.hzhr.iot.collect.sdk.model.command.setReportPeriod.SetReportPeriodModel;
import com.hzhr.iot.collect.sdk.model.command.setReportTime.SetReportTimeModel;
import com.hzhr.iot.collect.sdk.service.Collect_CommandService;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrJsonUtil;
import com.hzhr.iot.core.util.HzhrStringUtils;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.collectDevice.CollectDeviceModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDeviceModel;
import com.hzhr.iot.device.sdk.service.Device_CollectDeviceService;
import com.hzhr.iot.device.sdk.service.Device_IotDeviceService;
import com.hzhr.iot.web.Global;
import com.hzhr.iot.web.constant.DeviceOptions;
import com.hzhr.iot.web.controller.base.BaseController;
import com.hzhr.iot.web.dao_sm.SmCommandQueuesDao;
import com.hzhr.iot.web.dao_sm.SmDao;
import com.hzhr.iot.web.entity.SmCommandQueuesEntity;
import com.hzhr.iot.web.model.response.BaseResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "设备控制", description = "设备控制")
@RestController
@RequestMapping("/control")
public class ControlController extends BaseController {
    @Autowired
    Collect_CommandService collect_commandService;
    @Autowired
    Device_IotDeviceService device_iotDeviceService;
    @Autowired
    Global global;
    @Autowired
    DeviceOptions deviceOptions;
    @Autowired
    Device_CollectDeviceService device_collectDeviceService;
    @Autowired
    SmCommandQueuesDao smCommandQueuesDao;
    @Autowired
    SmDao smDao;


    @ApiOperation(value = "查询自醒上报时间", notes = "查询自醒上报时间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "collectdeviceid", value = "采集设备编号", dataType = "int", required = true, paramType = "query")
    }
    )
    @RequestMapping(value = "/searchrreporttime", method = RequestMethod.POST)
    BaseResponse searchrReportTime(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "0") int iotdeviceid
            , @RequestParam(value = "collectdeviceid", required = true,defaultValue = "0") int collectdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchReportTimeModel searchReportTimeModel = new SearchReportTimeModel();
        searchReportTimeModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchReportTime(header, 1, query, searchReportTimeModel);

        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "查询自醒上报周期", notes = "查询自醒上报周期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
    }
    )
    @RequestMapping(value = "/searchrreportperiod", method = RequestMethod.POST)
    BaseResponse searchrReportPeriod(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchReportPeriodModel searchReportPeriodModel = new SearchReportPeriodModel();
        searchReportPeriodModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchReportPeriod(header, 1, query, searchReportPeriodModel);

        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "查询冻结日", notes = "查询冻结日")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query")
    }
    )
    @RequestMapping(value = "/searchfreezingday", method = RequestMethod.POST)
    BaseResponse searchfreezingday(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "") String iotdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchFreezingDayModel searchFreezingDayModel = new SearchFreezingDayModel();
        searchFreezingDayModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchFreezingDay(header, 1, query, searchFreezingDayModel);

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "设置IP", notes = "设置IP")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "Integer", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ip", value = "ip", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "port", value = "端口", dataType = "Integer", required = true, paramType = "query")
    }
    )
    @RequestMapping(value = "/setIP", method = RequestMethod.POST)
    BaseResponse setIP(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "0") Integer iotdeviceid
            , @RequestParam(value = "ip", required = true,defaultValue = "") String ip
            , @RequestParam(value = "port", required = true,defaultValue = "") Integer port) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SetIpModel setIpModel = new SetIpModel();
        setIpModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        setIpModel.setIp(ip);
        setIpModel.setPort(port.toString());
        collect_commandService.setIp(header, 1, query, setIpModel);

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "查询IP", notes = "查询IP")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "Integer", required = true, paramType = "query")
    }
    )
    @RequestMapping(value = "/searchrIP", method = RequestMethod.POST)
    BaseResponse searchrIP(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "0") Integer iotdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchIpModel searchIpModel = new SearchIpModel();
        searchIpModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchIp(header, 1, query, searchIpModel);

        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "设置上报时间", notes = "设置上报时间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "waketime", value = "每天自醒时间(HHmmss),", dataType = "String", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "wakesec", value = "自醒时长(秒)", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "peakdelaysec", value = "选填,错峰延迟时间(单位：秒)", dataType = "int", required = false, paramType = "query"),
    }
    )
    @RequestMapping(value = "/setreporttime", method = RequestMethod.POST)
    BaseResponse setReportTime(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid
            , @RequestParam(value = "waketime", required = true) String waketime
//            , @RequestParam(value = "wakesec", required = false) String wakesec
            , @RequestParam(value = "peakdelaysec", required = false, defaultValue = "0") String peakdelaysec) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SetReportTimeModel setReportTimeModel = new SetReportTimeModel();
        setReportTimeModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        setReportTimeModel.setWaketime(waketime);
        collect_commandService.setReportTime(header, 1, query, setReportTimeModel);

        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "设置上报周期", notes = "设置上报周期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "period", value = "上报周期,必填(11)", dataType = "String", required = true, paramType = "query"),
    }
    )
    @RequestMapping(value = "/setreportperiod", method = RequestMethod.POST)
    BaseResponse setreportperiod(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid
            , @RequestParam(value = "period", required = true) String period) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SetReportPeriodModel setReportPeriodModel = new SetReportPeriodModel();
        setReportPeriodModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        if ("10000361".equals(period)) {
            setReportPeriodModel.setReportPeriod(deviceOptions.getCode("REPORT_PERIOD", "DAY"));
        } else if ("10000372".equals(period)) {
            setReportPeriodModel.setReportPeriod(deviceOptions.getCode("REPORT_PERIOD", "HOUR"));
        }
        collect_commandService.setReportPeriod(header, 1, query, setReportPeriodModel);

        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "设置冻结日", notes = "设置冻结日")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "freezingday", value = "冻结日,1-28", dataType = "String", required = true, paramType = "query"),
    }
    )
    @RequestMapping(value = "/setfreezingday", method = RequestMethod.POST)
    BaseResponse setfreezingday(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid
            , @RequestParam(value = "freezingday", required = true) String freezingday) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SetFreezingDayModel setFreezingDayModel = new SetFreezingDayModel();
        setFreezingDayModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        setFreezingDayModel.setFreezingDay(freezingday);
        collect_commandService.setFreezingDay(header, 1, query, setFreezingDayModel);

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "开阀", notes = "开阀")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "collectdeviceid", value = "采集设备编号", dataType = "String", required = false, paramType = "query"),
    }
    )
    @RequestMapping(value = "/openvalve", method = RequestMethod.POST)
    BaseResponse openValve(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "") String iotdeviceid
            , @RequestParam(value = "collectdeviceid", required = false,defaultValue = "") String collectdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("show_outId", true);

        CollectDeviceModel collectDeviceModel = null;

        if (!StringUtils.isEmpty(iotdeviceid) && !"undefined".equals(iotdeviceid)) {
            query.put("equal_id", iotdeviceid);
        } else {
            if (!StringUtils.isEmpty(collectdeviceid) && !"undefined".equals(collectdeviceid)) {
                String token1 = global.getFirstToken();
                Map<String, String> header1 = new HashMap<>();
                header1.put("token", token1);
                Map<String, Object> query1 = new HashMap<>();
                query1.put("show", "one");
                query1.put("show_info", true);
                query1.put("show_outId", true);
                query1.put("equal_id", collectdeviceid);
                collectDeviceModel = device_collectDeviceService.get(header1, query1).getModel();

                Integer iotDeviceId = collectDeviceModel.getIotDeviceId();
                if (iotDeviceId != null) {
                    query.put("equal_id", iotDeviceId);
                }
            }
        }
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        String categoryCode = iotDeviceModel.getCategoryCode();
        String outId = iotDeviceModel.getOutId();
        //如果是nb表，发送允许开阀
        if ("1".equals(categoryCode)) {
            header = new HashMap<>();
            header.put("token", global.getFirstToken());
            query = new HashMap<>();
            AllowOpenValveModel allowOpenValveModel = new AllowOpenValveModel();
            allowOpenValveModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
            collect_commandService.allowOpenValve(header, 1, query, allowOpenValveModel);
        }

        //如果是gprs物联网表，缓存指令到采集平台
        if ("2".equals(categoryCode)) {
            SmCommandQueuesEntity smCommandQueuesEntity = new SmCommandQueuesEntity();
            String seq = smDao.select1();
            String cmdId = HzhrDateUtil.dateToStr(new Date(), "yyMMdd") + HzhrStringUtils.fillZeroForLeft(seq, 8);
            smCommandQueuesEntity.setCmdId(cmdId);
            smCommandQueuesEntity.setPtId("15071700019401");
            smCommandQueuesEntity.setFcId("51");
            smCommandQueuesEntity.setCmdPriority(new Short("1"));
            smCommandQueuesEntity.setCmdStateId("1");
            smCommandQueuesEntity.setCmdTime(new Date());
            smCommandQueuesEntity.setDcId("6");
            Map<String, Object> map = smDao.select2(outId);
            smCommandQueuesEntity.setMeterId(HzhrTypeUtil.object2string(map.get("EQ_ID")));
            smCommandQueuesEntity.setEqId(HzhrTypeUtil.object2string(map.get("EQ_ID")));
            Map<String, Object> cmdMsgMap = new HashMap<>();
            cmdMsgMap.put("funcode", "3051");
            cmdMsgMap.put("direction", "0");
            cmdMsgMap.put("reqResp", "0");
            cmdMsgMap.put("logicAddr", iotDeviceModel.getCode());
            cmdMsgMap.put("orderSeq", cmdId);
            cmdMsgMap.put("pfId", null);
            cmdMsgMap.put("length", 0);
            cmdMsgMap.put("mac", null);
            cmdMsgMap.put("flagEnd", null);
            cmdMsgMap.put("echoCode", null);
            cmdMsgMap.put("ccrNO", null);
            cmdMsgMap.put("clrNO", null);
            cmdMsgMap.put("meterNO", null);
            cmdMsgMap.put("internetMeterNo", iotDeviceModel.getCode());
            smCommandQueuesEntity.setCmdMsg(JSONUtils.toJSONString(cmdMsgMap));
            smCommandQueuesEntity.setOrgId(HzhrTypeUtil.object2string(map.get("ORG_ID")));
            smCommandQueuesEntity.setVersion(new Short("0"));
            smCommandQueuesEntity.setOrderseq(cmdId);
            smCommandQueuesEntity.setFunctionCode("3051");
            smCommandQueuesEntity.setCmdSendnum(new Short("0"));
            smCommandQueuesDao.insert(smCommandQueuesEntity);
        }

        //如果是重燃lora表，缓存指令到采集平台，如果是自建lora表，发送开阀指令
        if ("3".equals(categoryCode) && collectDeviceModel != null) {
            if (StringUtils.isEmpty(outId)) {
                header = new HashMap<>();
                header.put("token", global.getFirstToken());
                query = new HashMap<>();
                OpenValve1Model openValve1Model = new OpenValve1Model();
                openValve1Model.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
                openValve1Model.setMeterNo(collectDeviceModel.getCode());
                collect_commandService.ccr_openValve(header, 2, query, openValve1Model);
            } else {
                SmCommandQueuesEntity smCommandQueuesEntity = new SmCommandQueuesEntity();
                String seq = smDao.select1();
                String cmdId = HzhrDateUtil.dateToStr(new Date(), "yyMMdd") + HzhrStringUtils.fillZeroForLeft(seq, 8);
                smCommandQueuesEntity.setCmdId(cmdId);
                smCommandQueuesEntity.setPtId("200000");
                smCommandQueuesEntity.setFcId("51");
                smCommandQueuesEntity.setCmdPriority(new Short("1"));
                smCommandQueuesEntity.setCmdStateId("1");
                smCommandQueuesEntity.setCmdTime(new Date());
                smCommandQueuesEntity.setDcId("2");
                String outId1 = collectDeviceModel.getOutId();
                smCommandQueuesEntity.setMeterId(HzhrTypeUtil.object2string(outId1));
                Map<String, Object> map1= smDao.select2(outId);
                smCommandQueuesEntity.setEqId(HzhrTypeUtil.object2string(map1.get("EQ_ID")));
                Map<String, Object> cmdMsgMap = new HashMap<>();
                cmdMsgMap.put("funcode", "2051");
                cmdMsgMap.put("direction", "0");
                cmdMsgMap.put("reqResp", "0");
                cmdMsgMap.put("logicAddr", iotDeviceModel.getCode());
                cmdMsgMap.put("orderSeq", cmdId);
                cmdMsgMap.put("pfId", null);
                cmdMsgMap.put("length", 0);
                cmdMsgMap.put("mac", null);
                cmdMsgMap.put("flagEnd", null);
                cmdMsgMap.put("echoCode", null);
                cmdMsgMap.put("ccrNO", iotDeviceModel.getCode());
                cmdMsgMap.put("clrNO", "0000000000");
                cmdMsgMap.put("meterNO", collectDeviceModel.getCode());
                cmdMsgMap.put("internetMeterNo", null);
                cmdMsgMap.put("ccrChannelNo", null);
                cmdMsgMap.put("meterType", null);
                smCommandQueuesEntity.setCmdMsg(JSONUtils.toJSONString(cmdMsgMap));
                smCommandQueuesEntity.setOrgId(HzhrTypeUtil.object2string(map1.get("ORG_ID")));
                smCommandQueuesEntity.setVersion(new Short("0"));
                smCommandQueuesEntity.setOrderseq(cmdId);
                smCommandQueuesEntity.setFunctionCode("2052");
                smCommandQueuesEntity.setCmdSendnum(new Short("0"));
                smCommandQueuesDao.insert(smCommandQueuesEntity);
            }
        }


        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "允许开阀", notes = "允许开阀")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "collectdeviceid", value = "采集设备编号", dataType = "String", required = false, paramType = "query"),
    }
    )
    @RequestMapping(value = "/allowopenvalue", method = RequestMethod.POST)
    BaseResponse allowopenvalue(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "") String iotdeviceid
            , @RequestParam(value = "collectdeviceid", required = false,defaultValue = "") String collectdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        AllowOpenValveModel allowOpenValveModel = new AllowOpenValveModel();
        allowOpenValveModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.allowOpenValve(header, 1, query, allowOpenValveModel);

        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "关阀", notes = "关阀")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "collectdeviceid", value = "采集设备编号", dataType = "String", required = false, paramType = "query"),
    }
    )
    @RequestMapping(value = "/closevalve", method = RequestMethod.POST)
    BaseResponse closeValve(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "") String iotdeviceid
            , @RequestParam(value = "collectdeviceid", required = false,defaultValue = "") String collectdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("show_outId", true);

        CollectDeviceModel collectDeviceModel = null;
        IotDeviceModel iotDeviceModel = null;

        if (!StringUtils.isEmpty(iotdeviceid) && !"undefined".equals(iotdeviceid)) {
            query.put("equal_id", iotdeviceid);
            iotDeviceModel = device_iotDeviceService.get(header, query).getModel();
        } else {
            if (!StringUtils.isEmpty(collectdeviceid) && !"undefined".equals(collectdeviceid)) {
                String token1 = global.getFirstToken();
                Map<String, Object> query1 = new HashMap<>();
                query1.put("show", "one");
                query1.put("show_info", true);
                query1.put("show_outId", true);
                query1.put("equal_id", collectdeviceid);
                collectDeviceModel = device_collectDeviceService.get(header, query1).getModel();

                if (collectDeviceModel != null) {
                    Integer iotDeviceId = collectDeviceModel.getIotDeviceId();
                    if (iotDeviceId != null) {
                        query.put("equal_id", iotDeviceId);
                    }
                }

                Map<String, String> header1 = new HashMap<>();
                header1.put("token", token1);
                iotDeviceModel = device_iotDeviceService.get(header1, query).getModel();
            }
        }

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "无设备权限");
        }

        String categoryCode = iotDeviceModel.getCategoryCode();
        String outId = iotDeviceModel.getOutId();
        //如果是nb表，发送关阀
        if ("1".equals(categoryCode)) {
            header = new HashMap<>();
            header.put("token", global.getFirstToken());
            query = new HashMap<>();
            CloseValveModel closeValveModel = new CloseValveModel();
            closeValveModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
            collect_commandService.closeValve(header, 1, query, closeValveModel);
        }

        //如果是gprs物联网表，缓存指令到采集平台
        if ("2".equals(categoryCode)) {
            SmCommandQueuesEntity smCommandQueuesEntity = new SmCommandQueuesEntity();
            String seq = smDao.select1();
            String cmdId = HzhrDateUtil.dateToStr(new Date(), "yyMMdd") + HzhrStringUtils.fillZeroForLeft(seq, 8);
            smCommandQueuesEntity.setCmdId(cmdId);
            smCommandQueuesEntity.setPtId("15071700019401");
            smCommandQueuesEntity.setFcId("52");
            smCommandQueuesEntity.setCmdPriority(new Short("1"));
            smCommandQueuesEntity.setCmdStateId("1");
            smCommandQueuesEntity.setCmdTime(new Date());
            smCommandQueuesEntity.setDcId("6");
            Map<String, Object> map = smDao.select2(outId);
            smCommandQueuesEntity.setMeterId(HzhrTypeUtil.object2string(map.get("EQ_ID")));
            smCommandQueuesEntity.setEqId(HzhrTypeUtil.object2string(map.get("EQ_ID")));
            Map<String, Object> cmdMsgMap = new HashMap<>();
            cmdMsgMap.put("funcode", "3052");
            cmdMsgMap.put("direction", "0");
            cmdMsgMap.put("reqResp", "0");
            cmdMsgMap.put("logicAddr", iotDeviceModel.getCode());
            cmdMsgMap.put("orderSeq", cmdId);
            cmdMsgMap.put("pfId", null);
            cmdMsgMap.put("length", 0);
            cmdMsgMap.put("mac", null);
            cmdMsgMap.put("flagEnd", null);
            cmdMsgMap.put("echoCode", null);
            cmdMsgMap.put("ccrNO", null);
            cmdMsgMap.put("clrNO", null);
            cmdMsgMap.put("meterNO", null);
            cmdMsgMap.put("internetMeterNo", iotDeviceModel.getCode());
            cmdMsgMap.put("ccrChannelNo", null);
            cmdMsgMap.put("meterType", null);
            smCommandQueuesEntity.setCmdMsg(JSONUtils.toJSONString(cmdMsgMap));
            smCommandQueuesEntity.setOrgId(HzhrTypeUtil.object2string(map.get("ORG_ID")));
            smCommandQueuesEntity.setVersion(new Short("0"));
            smCommandQueuesEntity.setOrderseq(cmdId);
            smCommandQueuesEntity.setFunctionCode("3052");
            smCommandQueuesEntity.setCmdSendnum(new Short("0"));
            smCommandQueuesDao.insert(smCommandQueuesEntity);
        }

        //如果是重燃lora表，缓存指令到采集平台，如果是自建lora表，发送关阀指令
        if ("3".equals(categoryCode) && collectDeviceModel != null) {
            if (StringUtils.isEmpty(outId)) {
                header = new HashMap<>();
                header.put("token", global.getFirstToken());
                query = new HashMap<>();
                CloseValve1Model closeValveModel = new CloseValve1Model();
                closeValveModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
                closeValveModel.setMeterNo(collectDeviceModel.getCode());
                collect_commandService.ccr_closeValve(header, 2, query, closeValveModel);
            } else {
                SmCommandQueuesEntity smCommandQueuesEntity = new SmCommandQueuesEntity();
                String seq = smDao.select1();
                String cmdId = HzhrDateUtil.dateToStr(new Date(), "yyMMdd") + HzhrStringUtils.fillZeroForLeft(seq, 8);
                smCommandQueuesEntity.setCmdId(cmdId);
                smCommandQueuesEntity.setPtId("200000");
                smCommandQueuesEntity.setFcId("52");
                smCommandQueuesEntity.setCmdPriority(new Short("1"));
                smCommandQueuesEntity.setCmdStateId("1");
                smCommandQueuesEntity.setCmdTime(new Date());
                smCommandQueuesEntity.setDcId("2");
                String outId1 = collectDeviceModel.getOutId();
                smCommandQueuesEntity.setMeterId(HzhrTypeUtil.object2string(outId1));
                Map<String, Object> map1= smDao.select2(outId);
                smCommandQueuesEntity.setEqId(HzhrTypeUtil.object2string(map1.get("EQ_ID")));
                Map<String, Object> cmdMsgMap = new HashMap<>();
                cmdMsgMap.put("funcode", "2052");
                cmdMsgMap.put("direction", "0");
                cmdMsgMap.put("reqResp", "0");
                cmdMsgMap.put("logicAddr", iotDeviceModel.getCode());
                cmdMsgMap.put("orderSeq", cmdId);
                cmdMsgMap.put("pfId", null);
                cmdMsgMap.put("length", 0);
                cmdMsgMap.put("mac", null);
                cmdMsgMap.put("flagEnd", null);
                cmdMsgMap.put("echoCode", null);
                cmdMsgMap.put("ccrNO", iotDeviceModel.getCode());
                cmdMsgMap.put("clrNO", "0000000000");
                cmdMsgMap.put("meterNO", collectDeviceModel.getCode());
                cmdMsgMap.put("internetMeterNo", null);
                cmdMsgMap.put("ccrChannelNo", null);
                cmdMsgMap.put("meterType", null);
                smCommandQueuesEntity.setCmdMsg(JSONUtils.toJSONString(cmdMsgMap));
                smCommandQueuesEntity.setOrgId(HzhrTypeUtil.object2string(map1.get("ORG_ID")));
                smCommandQueuesEntity.setVersion(new Short("0"));
                smCommandQueuesEntity.setOrderseq(cmdId);
                smCommandQueuesEntity.setFunctionCode("2052");
                smCommandQueuesEntity.setCmdSendnum(new Short("0"));
                smCommandQueuesDao.insert(smCommandQueuesEntity);
            }
        }

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "故障清除(9052)", notes = "故障清除(9052)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "alarmtype", value = "报警编号", dataType = "String", required = true, paramType = "query"),
    }
    )
    @RequestMapping(value = "/clearalarmevent", method = RequestMethod.POST)
    BaseResponse clearalarmevent(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid
            , @RequestParam(value = "alarmtype", required = true) String alarmtype) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        ClearFaultModel clearFaultModel = new ClearFaultModel();

        clearFaultModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        if ("10000191".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "QXGF"));
        } else if ("10000202".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "RQXL"));
        } else if ("10000213".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "CGQH"));
        } else if ("10000224".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "CCYC"));
        } else if ("10000235".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "QCGR"));
        } else if ("10000246".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "SBGZ"));
        } else if ("10000257".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "FMLQ"));
        } else if ("10000268".equals(alarmtype)) {
            clearFaultModel.setFault(deviceOptions.getCode("NB_FAULT", "DCGZ"));
        }

        collect_commandService.clearFault(header, 1, query, clearFaultModel);

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "异常查询(9053)", notes = "异常查询(9053)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "String", required = true, paramType = "query"),
    }
    )
    @RequestMapping(value = "/searchalarmevent", method = RequestMethod.POST)
    BaseResponse searchalarmevent(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchAlarmModel searchAlarmModel = new SearchAlarmModel();
        searchAlarmModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchAlarm(header, 1, query, searchAlarmModel);

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "日用量历史查询(9031)", notes = "日用量历史查询(9031)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "Integer", required = true, paramType = "query")
    }
    )
    @RequestMapping(value = "/searchdailyconsume", method = RequestMethod.POST)
    BaseResponse searchdailyconsume(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true, defaultValue = "0") Integer iotdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchDayHisModel searchDayHisModel = new SearchDayHisModel();
        searchDayHisModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchDayHis(header, 1, query, searchDayHisModel);

        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "月用量历史查询(9032)", notes = "月用量历史查询(9032)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceid", value = "物联网设备编号", dataType = "Integer", required = true, paramType = "query")
    }
    )
    @RequestMapping(value = "/searchmonthlyconsume", method = RequestMethod.POST)
    BaseResponse searchmonthlyconsume(@RequestParam(value = "uat", required = true) String uat
            , @RequestParam(value = "iotdeviceid", required = true,defaultValue = "0") Integer iotdeviceid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("show_info", true);
        query.put("equal_id", iotdeviceid);
        IotDeviceModel iotDeviceModel = device_iotDeviceService.get(header, query).getModel();

        if (iotDeviceModel == null) {
            return new BaseResponse("101", "物联网设备不存在");
        }

        header = new HashMap<>();
        header.put("token", global.getFirstToken());
        query = new HashMap<>();
        SearchMonthHisModel searchMonthHisModel = new SearchMonthHisModel();
        searchMonthHisModel.setDeviceId(iotDeviceModel.getIotPlatformDeviceId());
        collect_commandService.searchMonthHis(header, 1, query, searchMonthHisModel);

        return new BaseResponse("0", "成功");
    }
}
